package com.example.leoss.onclick_tmds;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.example.leoss.MyThread;
import com.example.leoss.R;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;


public class TongxunDownFragment extends Fragment  implements View.OnClickListener {

    private final static int FLAG=123;
    private Button mButtonConnection;
    private TextView mTextView;
    String content="http://47.100.203.0/download/教职工通讯录1.xls";
    private final static int MULTI_LINE = 1234;
    private int length;
    private ProgressBar mProgressBar1;
    private static final String DATA_TYPE_EXCEL = "application/vnd.ms-excel";
    private IntentFilter intentFilter;
    TextView textView;
    View view;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)   {

         view=inflater.inflate(R.layout.fragment_tongxun_down, container, false);
        setHasOptionsMenu(true);
        mButtonConnection = (Button)view.findViewById(R.id.button_connection12);
        mButtonConnection.setOnClickListener(this);
        mProgressBar1 = (ProgressBar) view.findViewById(R.id.progressbar12);
        textView=view.findViewById(R.id.moban_textview);

       // ZoomImageView zoomImageView=new ZoomImageView(mContext);


        return view;
    }
        @SuppressLint("HandlerLeak")
    private Handler handle = new Handler()
    {

        @Override
        public void handleMessage(Message msg)
        {
            switch (msg.what)
            {
                case MULTI_LINE:
                    int progress = msg.arg1;
                    mProgressBar1.setProgress(msg.arg1 * 100 / length);
                    break;
            }
        }


    };


    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {

        super.onCreateOptionsMenu(menu, inflater);
        getActivity().getMenuInflater().inflate(R.menu.moban_meun,menu);
    }



    @SuppressLint("SetTextI18n")
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId())
        {
           case  R.id.conputer:

textView.setText("http://47.100.203.0/download/教职工通讯录1.xls");
Toast.makeText(getActivity(),"长按分享或复制",Toast.LENGTH_LONG).show();
               break;
            case  R.id.liulianqi:
                openBrowser(getActivity(),"http://47.100.203.0/download/教职工通讯录1.xls");break;
        }
        return super.onOptionsItemSelected(item);
    }





    /**
     * 判断文件是否存在
     * @param strFile
     * @return
     */
    public boolean fileIsExists(String strFile)
    {
        try
        {
            File f=new File(strFile);
            if(!f.exists())
            {
                return false;
            }

        }
        catch (Exception e)
        {
            return false;
        }

        return true;
    }


    private void MYther() {
        new Thread( new Runnable()
        {

            @Override
            public void run()
            {
                String urlString = content;
                // 连接网络的权限不要忘记添加
                URL url;
                try
                {
                    url = new URL(urlString);
                    HttpURLConnection connect = (HttpURLConnection) url.openConnection();
                    //获得传输内容的长度
                    length = connect.getContentLength();
                    InputStream input = connect.getInputStream();
                    //定义要写入文件的路径
                    File file = new File("/sdcard/AndroidTest/", "教职工通讯录1.xls");
                    //当文件不存在时创建文件

                    if (!file.exists()) {
                        file.createNewFile();
                    }
                    MyThread[] threads = new MyThread[5];
                    for (int i = 0; i < 5; i++)
                    {
                        //开启自定义的线程，并传入相应的值
                        MyThread thread = null;
                        if (i == 4) {
                            //最后一个文件传输的内容可能不为整数，所以要单独拿出来进行传输
                            thread = new MyThread(length / 5 * 4, length, urlString, file.getAbsolutePath());
                        } else {
                            //注意减一
                            thread = new MyThread(length / 5 * i, length / 5 * (i + 1)-1, urlString,
                                    file.getAbsolutePath());
                        }
                        //开启线程
                        thread.start();
                        threads[i] = thread;
                    }

                    //但没有下载完时，不断对已经下载的数量进行更新。
                    boolean isFinish = true;
                    while (isFinish)
                    {
                        int sum = 0;
                        for (MyThread thread : threads) {
                            sum += thread.getSum();
                        }


                        Message msg = handle.obtainMessage();
                        msg.what = MULTI_LINE;
                        msg.arg1 = sum;
                        handle.sendMessage(msg);
                        if (sum + 10 >= length)
                        {
                            isFinish = false;
                        }
                        //下载完时，线程休眠
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }

                } catch (MalformedURLException e) {
                    e.printStackTrace();
                }
                catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }).start();

    }
    @Override
    public void onClick(View v) {
        switch (v.getId())
        {
            case R.id.button_connection12:

                if (!fileIsExists("/sdcard/AndroidTest/教职工通讯录1.xls"))
                {
                    //文件不存在开启一个线程去下载
                    MYther();
                    //下载成功提示
                    Toast.makeText(getContext(),"下载成功AndroidTest/教职工通讯录1.xls文件",Toast.LENGTH_LONG).show();
                    openFile(getActivity(), new File("/storage/emulated/0/AndroidTest/教职工通讯录1.xls"));

                }else
                {

                    Toast.makeText(getContext(),"已下载到AndroidTest/教职工通讯录1.xls文件",Toast.LENGTH_LONG).show();

                    openFile(getActivity(), new File("/storage/emulated/0/AndroidTest/教职工通讯录1.xls"));
                }
                break;
        }
    }


    /**
     * 浏览器下载XLS文件
     * @param context
     * @param url
     */
    public static  void openBrowser(Context context,String url)
    {
        try {  final Intent intent = new Intent();
            intent.setAction(Intent.ACTION_VIEW);
            intent.setData(Uri.parse(url));
            // 注意此处的判断intent.resolveActivity()可以返回显示该Intent的Activity对应的组件名
            // 官方解释 : Name of the component implementing an activity that can display the intent
            if (intent.resolveActivity(context.getPackageManager()) != null) {
                final ComponentName componentName = intent.resolveActivity(context.getPackageManager());
                // 打印Log   ComponentName到底是什么
                Log.e("componentName = ","" + componentName.getClassName());
                context.startActivity(Intent.createChooser(intent, "请选择浏览器"));
            } else {
                Toast.makeText(context.getApplicationContext(), "请下载浏览器", Toast.LENGTH_SHORT).show();
            }


        }catch (Exception e){
            Log.e("",""+e.toString());
        }

    }

    /**
     * Provide使用手机浏览器打开XLS文件
     * @param activityFrom
     * @param file
     */
    public static void openFile(Activity activityFrom, File file)
    {
        Intent intent = new Intent();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //  此处注意替换包名，
            Uri contentUri = FileProvider.getUriForFile(activityFrom, "com.example.leoss.fileProvider", file);
            Log.e("file_open", " uri   " + contentUri.getPath());
            intent.setDataAndType(contentUri,"application/vnd.ms-excel");
//            intent.setDataAndType(contentUri, "image/*");
        } else {
            intent.setDataAndType(Uri.fromFile(file),"application/vnd.ms-excel");//也可使用 Uri.parse("file://"+file.getAbsolutePath());
        }

        //以下设置都不是必须的
        intent.setAction(Intent.ACTION_VIEW);// 系统根据不同的Data类型，通过已注册的对应Application显示匹配的结果。
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//系统会检查当前所有已创建的Task中是否有该要启动的Activity的Task
        //若有，则在该Task上创建Activity；若没有则新建具有该Activity属性的Task，并在该新建的Task上创建Activity。
        intent.addCategory(Intent.CATEGORY_DEFAULT);//按照普通Activity的执行方式执行
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        activityFrom.startActivity(intent);
    }
}
